package com.hpin.fansea.sale;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.alipay.AlipayEx;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.GoodsDetailBean;
import com.hpin.fansea.bean.OrderDelvEntity;
import com.hpin.fansea.bean.OrderEntity;
import com.hpin.fansea.bean.PropOrdeBean;
import com.hpin.fansea.utils.CommonUtils;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.hpin.fansea.utils.LogUtil;
import com.hpin.fansea.wxapi.WXKeys;
import com.hpin.fansea.wxapi.WXPayEx;
import com.lidroid.xutils.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**
 * 支付页面
 * Created by Aaron on 15/10/22.
 */
public class PurchasePayAcrivity extends BaseActivity {

    private static final int REQUEST_RED = 2;
    private RelativeLayout purchase_pay_rlAddress;

//    private RelativeLayout pay_weixin;
    private RelativeLayout pay_kuaijie;

    private Intent mIntent;
    // 微信支付
    private WXPayEx wxpe = new WXPayEx();
    private ImageView purchase_pay_image;
    private TextView purchase_pay_tittle;
    private TextView purchase_pay_TgPrice;
    private TextView purchase_pay_price;
    private TextView purchase_pay_comment;
    private Button pay_add_num;
    private EditText pay_et_num;
    private Button pay_reduce_num;
    private TextView purchase_pay_submit;
    //    public Handler mhandler;
    public static Activity mContext;
    //    PurchaseGflist goodsDetal;
    private TextView purchase_pay_content;
    double price;// 商品单价
    double payCash;// 实际支付金额 减过红包
    double ordCash;// 总价 订单金额
    //    double redPacketCash;// 使用红包金额
    private int currentNum;// 当前订单数量
    private TextView purchase_payCash;
    private TextView purchase_ordCash;

//    private CheckBox pay_weixin_check;
    private CheckBox pay_kuaijie_check;// 支付宝快捷支付

    private String orderNo = "";// 订单编号
//    private MyRedPacket myRedPacket = null;

    //获取到用户填写的有效的地址  (传给服务器的)
    private String realName;
    private String realAddress;
    private String realTel;
    private GoodsDetailBean.GoodsResult goodsDetal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_purchase_pay);

        mContext = PurchasePayAcrivity.this;
//        mhandler = new MyHandler();

        float scale = getResources().getDisplayMetrics().density;

        price = 0.0;
        payCash = 0.0;
        ordCash = 0.0;
//        redPacketCash = 0.0;
        currentNum = 1;
//        goodsDetal = (PurchaseGflist) getIntent().getSerializableExtra("goodsDetal");

        goodsDetal = (GoodsDetailBean.GoodsResult) getIntent().getSerializableExtra("goodsDetal");

        initFindViewById();

        //sp中获得默认的地址
        getDefaultAddress();

        initData();

        //收件地址
        userAddress = sp.getString(Constant.communityId, "") + "期" + sp.getString(Constant.buildingNo, "") +
                sp.getString(Constant.unitNo, "") + sp.getString(Constant.houseNo, "");

        //微信支付 初始化
        wxpe.initWXAPI(this);
        final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(WXKeys.APP_ID);
//        //注册微信支付广播
//        registerReceiver(wxReceiver, new IntentFilter(Constant.PAY_MSG));
    }

    /**
     * sp中获取默认的地址
     */
    private void getDefaultAddress() {

        //获取本地保存的默认的收货人,地址,电话
        String default_people = sp.getString(Constant.DEFAULT_PEOPLE, "");
        String default_address = sp.getString(Constant.DEFAULT_ADDRESS, "");
        String default_tel = sp.getString(Constant.DEFAULT_TEL, "");

        if (!TextUtils.isEmpty(default_tel) && !TextUtils.isEmpty(default_people) && !TextUtils.isEmpty(default_address)) {
            //有默认地址
            tv_write_address.setVisibility(View.INVISIBLE);
            //设置参数
            realName = default_people;
            realAddress = default_address;
            realTel = default_tel;

            tv_name.setText(default_people);
            tv_tel.setText(default_tel);
            tv_detail.setText(default_address);

        } else {
            //无默认地址
            iv_head.setVisibility(View.INVISIBLE);
            iv_tel.setVisibility(View.INVISIBLE);
        }

    }

    private void initFindViewById() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);

        iv_left.setOnClickListener(this);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);

        tv_title.setText("结算中心");

        iv_head = (ImageView) findViewById(R.id.iv_head);
        iv_tel = (ImageView) findViewById(R.id.iv_tel);
        tv_write_address = (TextView) findViewById(R.id.tv_write_address);
        // 联系人
        tv_name = (TextView) findViewById(R.id.tv_name);
        //联系人电话
        tv_tel = (TextView) findViewById(R.id.tv_tel);
        //详细地址
        tv_detail = (TextView) findViewById(R.id.tv_detail);

        purchase_pay_image = (ImageView) findViewById(R.id.purchase_pay_image);
        purchase_pay_tittle = (TextView) findViewById(R.id.purchase_pay_tittle);
        purchase_pay_content = (TextView) findViewById(R.id.purchase_pay_content);
        purchase_pay_TgPrice = (TextView) findViewById(R.id.purchase_pay_TgPrice);
        purchase_pay_price = (TextView) findViewById(R.id.purchase_pay_price);
        purchase_pay_comment = (TextView) findViewById(R.id.purchase_pay_comment);
        pay_add_num = (Button) findViewById(R.id.pay_add_num);
        pay_et_num = (EditText) findViewById(R.id.pay_et_num);
        pay_reduce_num = (Button) findViewById(R.id.pay_reduce_num);
        purchase_payCash = (TextView) findViewById(R.id.purchase_payCash);

        purchase_ordCash = (TextView) findViewById(R.id.purchase_ordCash);
        purchase_pay_submit = (TextView) findViewById(R.id.purchase_pay_submit);
        purchase_pay_rlAddress = (RelativeLayout) findViewById(R.id.purchase_pay_rlAddress);

//        pay_weixin = (RelativeLayout) findViewById(R.id.purchase_pay_rl_weixin);

        pay_kuaijie = (RelativeLayout) findViewById(R.id.purchase_pay_rl_kuaijie);
//        pay_weixin_check = (CheckBox) findViewById(R.id.pay_weixin_check);
        pay_kuaijie_check = (CheckBox) findViewById(R.id.pay_kuaijie_check);

        purchase_pay_submit.setOnClickListener(this);
        pay_add_num.setOnClickListener(this);
        pay_reduce_num.setOnClickListener(this);
//        pay_weixin.setOnClickListener(this);
        pay_kuaijie.setOnClickListener(this);
        purchase_pay_rlAddress.setOnClickListener(this);

        pay_et_num.addTextChangedListener(textWatcher);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        LogUtil.d("purchase", " purchase ========== onNewIntent ==========");

        realName = intent.getStringExtra("realName");
        realAddress = intent.getStringExtra("realAddress");
        realTel = intent.getStringExtra("realTel");

        if (!TextUtils.isEmpty(realName) && !TextUtils.isEmpty(realAddress) && !TextUtils.isEmpty(realTel)) {
            tv_write_address.setVisibility(View.INVISIBLE);

            iv_head.setVisibility(View.VISIBLE);
            iv_tel.setVisibility(View.VISIBLE);
            //设置内容
            tv_name.setText(realName);
            tv_tel.setText(realTel);
            tv_detail.setText(realAddress);

        }

    }

    // 监听数量输入
    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            Log.d("TAG", "onTextChanged--------------->");
            String str = pay_et_num.getText().toString();
            try {

                int num = 0;
                if (str.length() > 0)
                    num = Integer.parseInt(str);
                updateCash(num);

            } catch (Exception e) {

            }

        }
    };

    /**
     * 更新金额显示
     *
     * @param num
     */
    private void updateCash(int num) {
        currentNum = num;
        payCash = currentNum * price;
        ordCash = currentNum * price;

//        // 选择红包数大于要支付的价格
//        if (redPacketCash > ordCash) {
//            payCash = 0;
//            // showToast("红包超出总价");
//        } else {
//            // 判断是否超出限额
//            if (currentNum * price - redPacketCash < 0) {
//                payCash = 0;
//                showToast("红包使用超出限额");
//            } else {
//                payCash = currentNum * price - redPacketCash;
//            }
//        }

        payCash = CommonUtils.float2(payCash);
        ordCash = CommonUtils.float2(ordCash);
        purchase_payCash.setText(payCash + "元");
        purchase_ordCash.setText(ordCash + "元");
    }

//    // 微信广播接收器(用于接受 微信和支付宝 支付完成的广播)
//    private BroadcastReceiver wxReceiver = new BroadcastReceiver() {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String payResult = intent.getStringExtra("pay_status");
//            submitPayResult(payResult);
//            if (payResult != null && payResult.equals(Constant.STATUS_SUCESS)) {
//                // 跳转订单页面
////                Intent intent1 = new Intent(PurchasePayAcrivity.this , MyPurchaseActivity.class);
////                startActivity(intent1);
//
//                LogUtil.d("TAG", "支付完成发送广播-=====================>>>>>>");
////				int i = 0;
////				showToast("支付完成发送广播" + ++i);
//
//                Intent payIntent = new Intent();
//                payIntent.setAction(Constant.REFREE_COMMENT_PAY);
//                sendBroadcast(payIntent);
//
//                finish();
//
////				PurchaseGfDetailActivity.mContext.finish();
//            }
//        }
//    };
    //    private TextView tv_myleft_redpacket;// 我的剩余红包
    private String userAddress;// 用户的默认地址
    private String discountCount;
    //    private TextView tv_yuan;
    private ImageView iv_head;
    private ImageView iv_tel;
    private TextView tv_write_address;
    private TextView tv_name;
    private TextView tv_tel;
    private TextView tv_detail;

    /**
     * 提交支付结果
     *
     * @param payResult
     */
    private void submitPayResult(String payResult) {

        String payType = getPayType();

//        DataService.getPurchasePAY(orderNo, payResult, payType, mhandler);

        RequestParams params = new RequestParams();
        params.addBodyParameter("token", sp.getString(Constant.token, ""));
        params.addBodyParameter("orderId", orderNo);
        params.addBodyParameter("payResult", payResult);
        params.addBodyParameter("systemType", Constant.SYSTEM_TYPE);
        params.addBodyParameter("payMethod", payType);
        HttpUtil.getInstance().setPostRequest("正在提交中支付结果", this, Constant.WEB_ROOT + Constant.PURCHASEPAY, params, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

            }
        }, null);

    }

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        unregisterReceiver(wxReceiver);
//    }

    private void initData() {

        // 标题
        purchase_pay_tittle.setText(goodsDetal.name);

        // 二级标题
        purchase_pay_content.setText(goodsDetal.title);

        // 图片
        ImageLoader.getInstance().displayImage(goodsDetal.fmpica, purchase_pay_image);

        // 图片
        if (!TextUtils.isEmpty(goodsDetal.reviewNum)) {
            purchase_pay_comment.setText("评论数:" + goodsDetal.reviewNum + "条");

        } else {
            purchase_pay_comment.setText("评论数:0条");
        }
        // 团购价
        if (!TextUtils.isEmpty(goodsDetal.tgPr)) {
            purchase_pay_TgPrice.setText(goodsDetal.tgPr + "元");
            // 单价
            price = Double.parseDouble(goodsDetal.tgPr.toString());
            payCash = price;
            ordCash = price;
            purchase_payCash.setText(payCash + "元");
            purchase_ordCash.setText(payCash + "元");
        }

        // 销售价
        if (!TextUtils.isEmpty(goodsDetal.salePr)) {
            purchase_pay_price.getPaint().setFlags(
                    Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰
            purchase_pay_price.setText(goodsDetal.salePr + "元");
        }
        // 默认订单数量
        pay_et_num.setText(currentNum + "");

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        //收货地址
        if (requestCode == REQUEST_RED && resultCode == 4) {
            LogUtil.d("purchase", " purchase ========== onActivityResult ==========");

            if (data != null) {

                realName = data.getStringExtra("realName");
                realAddress = data.getStringExtra("realAddress");
                realTel = data.getStringExtra("realTel");

                if (!TextUtils.isEmpty(realName) && !TextUtils.isEmpty(realAddress) && !TextUtils.isEmpty(realTel)) {
                    tv_write_address.setVisibility(View.INVISIBLE);

                    iv_head.setVisibility(View.VISIBLE);
                    iv_tel.setVisibility(View.VISIBLE);
                    //设置内容
                    tv_name.setText(realName);
                    tv_tel.setText(realTel);
                    tv_detail.setText(realAddress);

                }

            }
        }
    }

    /**
     * 获取支付类型
     *
     * @return
     */
    private String getPayType() {
        String payType = "";

//        if (pay_weixin_check.isChecked()) {
//            payType = Constant.PAYMETHOD_WEIXIN;
//        } else

        if (pay_kuaijie_check.isChecked()) {
            payType = Constant.PAYMETHOD_ZHIFUBAO;
        }

        return payType;
    }

    /**
     * 下单
     *
     * @return
     */
    private void makeOrder() {
        // 游客身份
        if (Constant.STATUS_VISITOR.equals(sp.getString(Constant.status, ""))) {
            remindLogin("亲,登录后才能支付哦");
            return;
        }
        // if (pay_contact.getText().toString().length() < 2
        // || pay_contact.getText().toString().length() > 4) {
        // showToast("联系人应在2-4个字符");
        // return;
        // }

        if (TextUtils.isEmpty(realName) || TextUtils.isEmpty(realAddress) || TextUtils.isEmpty(realTel)) {
            showToast("请补齐您的收货地址哦,亲~");
            return;
        }

        String payType = getPayType();
        if (payType.length() == 0) {
            showToast("请选择支付方式");
            return;
        }

        // 订单json
        OrderEntity json = new OrderEntity();
        json.grbuyId = goodsDetal.id_;// 团购ID
        json.groupBuyTitle = goodsDetal.title;// 团购标题

        // 获取用户姓名
        json.memName = realName;// 用户姓名
        json.mobNo = realTel;// 电话
        json.createId = sp.getString(Constant.userId, "");// 创建人id 手机号
        json.ordFrom = Constant.SYSTEM_TYPE;// 订单来源
        // // 获取配送方式
        // String delvMethod = "";
        // if (radio1.isChecked()) {
        // // 送货上门
        // delvMethod = Constant.DELV_PROPERTY;
        // } else if (radio2.isChecked()) {
        // // 用户自取
        // delvMethod = Constant.DELV_USER;
        // }
        json.delvMethod = Constant.DELV_PROPERTY;// 配送方式
        json.orderType = Constant.ORDER_PURCHASE;// 订单类型
        json.groupBuyNum = pay_et_num.getText().toString();// 团购数量
        json.noPayment = payCash + "";// 待支付
//        json.redPacketCash(pay_used_red.getText().toString());// 红包金额
        json.ordCash = ordCash + "";// 订单金额
        json.payCash = payCash + "";// 实际支付金额
        String order = JSON.toJSONString(json);

        // 地址json
        OrderDelvEntity json2 = new OrderDelvEntity();
        json2.setRcvrName(realName);// 收货人名
        json2.setAddr4(realAddress);// 地址
        json2.setMobTelNo(realTel);// 手机号

        String orderDelv = JSON.toJSONString(json2);

        RequestParams params = new RequestParams();

        params.addBodyParameter("token", sp.getString(Constant.token, ""));
        params.addBodyParameter("order", order);
        params.addBodyParameter("orderDelv", orderDelv);
        params.addBodyParameter("systemType", Constant.SYSTEM_TYPE);
        params.addBodyParameter("payMethod", payType);

        HttpUtil.getInstance().setPostRequest("正在下单", this, Constant.WEB_ROOT + Constant.PURCHASEORDER, params, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                try {

                    PropOrdeBean propOrdeBean = JSONObject.parseObject(str, PropOrdeBean.class);

                    if (Constant.STATUS_SUCESS.equals(propOrdeBean.status)) {

                        // 团购下单成功
                        payOrder(propOrdeBean);

                    } else {
                        showToast(propOrdeBean.message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("下单失败");
                }

            }
        }, null);

    }

    /**
     * 启动支付
     *
     * @param
     */
    private void payOrder(PropOrdeBean propOrdeBean) {

        if (propOrdeBean.result == null)
            return;

//        String payType = Constant.PAYMETHOD_ZHIFUBAO;

//        if (payType.equals(Constant.PAYMETHOD_WEIXIN)) {// 微信支付
//
//            //前两步服务器完成, app端只有掉起支付就行
//            wxpe.doStartWXPay(propOrdeBean.result.prepayid, propOrdeBean.result.nonce_str,
//                    propOrdeBean.result.timestamp, propOrdeBean.result.package_, propOrdeBean.result.sign);
//
//            //商品支付
//            mApplication.wxPayType = Constant.PAY_GOODS;
//        } else
//        if (payType.equals(Constant.PAYMETHOD_ZHIFUBAO)) {// 支付宝支付

        AlipayEx.doStartAlipay(Constant.PAY_GOODS, this, propOrdeBean.result.out_trade_no,
                    propOrdeBean.result.subject, propOrdeBean.result.body, propOrdeBean.result.total_fee,
                    propOrdeBean.result.notify_url, propOrdeBean.result.return_url);
//        }
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:

                finish();

                break;
            case R.id.purchase_pay_submit:

                makeOrder();

                break;
            case R.id.pay_add_num:
                // 增加数量按钮

                currentNum++;
                pay_et_num.setText(currentNum + "");
//                    payCash = currentNum * price - redNum1;
                ordCash = currentNum * price;
                payCash = CommonUtils.float2(payCash);
                ordCash = CommonUtils.float2(ordCash);
                purchase_payCash.setText(payCash + "元");
                purchase_ordCash.setText(ordCash + "元");

                break;
            case R.id.pay_reduce_num:
                // 减少数量不能少于1
                if (currentNum > 1) {
                    currentNum--;
                    pay_et_num.setText(currentNum + "");
//                            payCash = currentNum * price - redNum2;
                    ordCash = currentNum * price;
                    payCash = CommonUtils.float2(payCash);
                    ordCash = CommonUtils.float2(ordCash);
                    purchase_payCash.setText(payCash + "元");
                    purchase_ordCash.setText(ordCash + "元");

                }
                break;
            case R.id.purchase_pay_rlAddress:

                // 收货地址
                mIntent = new Intent(this, ChooseReceiveAddressActivity.class);
                startActivityForResult(mIntent, REQUEST_RED);
                break;

//            case R.id.purchase_pay_rl_weixin:
//                // 微信
//                pay_weixin_check.setChecked(true);
//                pay_kuaijie_check.setChecked(false);
//                break;

            case R.id.purchase_pay_rl_kuaijie:
                // 支付宝快捷支付
//                pay_weixin_check.setChecked(false);
                pay_kuaijie_check.setChecked(true);

                break;
            default:
                break;
        }
    }
}
